package com.axend.aerosense.common.connect.ble.handler;

import com.axend.aerosense.base.utils.ByteUtils;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.common.connect.bean.BleMsgEntity;
import com.axend.aerosense.common.connect.bean.BleMsgTag;
import com.axend.aerosense.common.connect.bean.BleNotifyEntity;
import com.axend.aerosense.common.connect.ble.AbstractBleMsgProcessor;
import com.blankj.utilcode.util.LogUtils;

import java.nio.charset.StandardCharsets;

/**
 * 获取设备ID（统一13字节长度）（雷达板）（需要注意设备开头协议的魔术位）
 * 协议：magic(1 bytes) ver(1 bytes) type(1 bytes) cmd(1 bytes) req id(int 4byte)  timeout(short 2byte) content len (int) 标识符 (2 bytes) 数据内容
 */
public class BleDeviceIdHandler extends AbstractBleMsgProcessor {

    @Override
    protected BleMsgTag getMsgTag() {
        return BleMsgTag.GET_DEVICE_ID;
    }

    @Override
    public byte[] write(BleMsgEntity bleMsgEntity) {
        byte[] bytes = ByteUtils.hexStringToBytes("130101019B000000102700000006041000000000");
        RadarType radarType = bleMsgEntity.getRadarType();

        //Assure雷达不走蓝牙协议
        if (radarType != RadarType.ASSURE) {
            bytes[0] = radarType.getMagic();
        }

        return bytes;
    }

    @Override
    public BleNotifyEntity processor(BleNotifyEntity notifyEntity) {
        if (null == notifyEntity) {
            LogUtils.w("notifyEntity is null");
            return null;
        }

        byte[] bytes = (byte[]) notifyEntity.getData();

        if (isNull(bytes)) {
            LogUtils.w("bytes length 0");
            return null;
        }

        if (bytes.length != 13) {
            LogUtils.d("Device ID length is abnormal", "length: " + bytes.length);
        }

        String id = ByteUtils.bytesToHexString(bytes);
        return new BleNotifyEntity(getMsgTag(), id);
    }
}
